package com.tg.app.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.demo.view.SettingItemSwitchView;
import com.tg.app.R;
import com.tg.message.msg.NotificationSetting;

import java.util.ArrayList;
import java.util.List;

public class NotificationSettingAdapter extends BaseAdapter {

    private final List<NotificationSetting> list = new ArrayList<>();
    private Context context;

    public NotificationSettingAdapter(Context context){
        this.context = context;
    }

    public void update(List<NotificationSetting> l) {
        list.clear();
        list.addAll(l);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null){
            holder = new ViewHolder();

            convertView = LayoutInflater.from(context).inflate(R.layout.notification_settings_item,null);

            holder.item = convertView.findViewById(R.id.switch_view);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }

        final NotificationSetting notificationSetting = list.get(position);

        holder.item.setChecked(notificationSetting.enabled);
        holder.item.setText(notificationSetting.mainLabel);

        holder.item.setOnClickListener(v -> {
            onSwitchListener.onSwitchStatusChanged(holder.item.isChecked(), notificationSetting, position, holder.item);
        });

        return convertView;
    }

    public final class ViewHolder {
        public SettingItemSwitchView item;
    }

    private OnSwitchListener onSwitchListener;

    public void setOnSwitchListener(OnSwitchListener onSwitchListener) {
        this.onSwitchListener = onSwitchListener;
    }

    public interface OnSwitchListener {
        void onSwitchStatusChanged(boolean isEnable, NotificationSetting notificationSetting, int position, SettingItemSwitchView settingItemSwitchView);
    }
}
